import { ipcRenderer, shell } from "electron";
import React, { useEffect, useState } from "react";
import { downloadFilesByUrl, sleep } from "../../../utils/tools";
import fs from 'fs';
import { getFileName, getFileNameFromid } from "../../../utils/message-input-util";
import Toast from "../../../components/toast/Toast";

const PicElemItem = (props: any): JSX.Element => {  //用usestate可能出问题,fixed:在最外层加key
    const {image_elem_orig_url,image_elem_orig_id,file_elem_file_id}=props
    const [urlState,seturlState]= useState("");
    const [localurl,setLocalUrl]= useState("");
    const showPic = () => {
        // try {
        //     if(localurl.length>0){
        //         shell.openPath(localurl).catch(err=>{
        //             shell.showItemInFolder(localurl)
        //         })
        //     }
        // }catch {}
        //openLocalImg(localurl);
        //window.open(urlState);
        const newWindow = window.open('','显示图片','toolbar=no,menubar=no');
        newWindow.document.body.innerHTML =`<div style='text-align: center;'> <img style='max-height: 900px;' src='${urlState}' /></div>`;
    }
    const setLocalSrc= (file_path:string)=>{
        setLocalUrl(file_path);
        const buf = fs.readFileSync(file_path);
        const bolb = new Blob([buf]);
        seturlState(URL.createObjectURL(bolb));
    }
    const listener = async (event, params) => {
        const fileName = getFileName(image_elem_orig_url);
        const {file_path} = params;
        //console.log(params);console.log(fileName)  --回调和本次的调用不一定能对得上
        if(file_path.includes(fileName)){
            // if(isNew&&!image_elem_orig_id){
            //     try {
            //         await aesFileDecry(file_path);
            //         await sleep(500); //连续加密多图时会报错
            //     }catch(ex){
            //         console.log(ex);
            //         return;
            //     }
            // }
            setLocalSrc(file_path);
        }
    }
    useEffect(() => {
        if(file_elem_file_id){
            const file = Toast.downPath +"\\"+  getFileNameFromid(file_elem_file_id);
            //console.log(file);
            if(fs.existsSync(file)){
                setLocalSrc(file);
            }else{
                ipcRenderer.on("DOWNLOADFILE_CALLBACK", listener);
                downloadFilesByUrl(image_elem_orig_url,true) 
            }
        }
        return ()=>{
            ipcRenderer.off("DOWNLOADFILE_CALLBACK", listener)
        }
    }, [file_elem_file_id])    //这里props变化时需要执行的操作，否则可能出问题

    const handleError = async ()=>{
        if(localurl.length>0){
            console.log("img err:"+ localurl);
            if(fs.existsSync(localurl)){
                fs.rmSync(localurl);
                await sleep(2000);  //删除后不能立即下载
            } 
            setLocalUrl('');
            downloadFilesByUrl(image_elem_orig_url,true) ;
        }  
    }

    return  (
        <div className="message-view__item--text pic right-menu-item" onDoubleClick={showPic}>
            <img src={urlState} style={{ maxWidth: '230px' }} onError={handleError}></img>
        </div>
    )
}
const isEuqre = (prevProps, curProps) =>{
    const iseque = prevProps.file_elem_file_id ==curProps.file_elem_file_id;
    return iseque;
}
export default  React.memo(PicElemItem,isEuqre);